package org.mall.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.mall.common.api.vo.Result;
import org.mall.common.constant.CommonStatusEnum;
import org.mall.common.util.ObjectUtils;
import org.mall.modules.pojo.product.dto.CommoditySkuDTO;
import org.mall.modules.pojo.product.vo.ParamVo;
import org.mall.modules.product.entities.CommoditySku;
import org.mall.modules.product.entities.CommoditySpu;
import org.mall.modules.product.entities.ProductMsg;
import org.mall.modules.product.mapper.CommoditySkuMapper;
import org.mall.modules.product.mapper.CommoditySpuMapper;
import org.mall.modules.product.service.ICommoditySpuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 商品SPU
 * @Author: jeecg-boot
 * @Date:   2019-11-07
 * @Version: V1.0
 */
@Service
public class CommoditySpuServiceImpl extends ServiceImpl<CommoditySpuMapper, CommoditySpu> implements ICommoditySpuService {

    @Resource
    private CommoditySpuMapper commoditySpuMapper;
    @Resource
    private CommoditySkuMapper commoditySkuMapper;

    @Override
    @Transactional
    public void saveMain(CommoditySpu spu, List<CommoditySku> skuList) {
        spu.setDefaultItemId(skuList.size()>0?skuList.get(0).getId():null);
        commoditySpuMapper.insert(spu);
        commoditySkuMapper.saveBatch(skuList);
    }

    @Override
    @Transactional
    public void updateMain(CommoditySpu spu,List<CommoditySku> skuList) {
        commoditySpuMapper.updateById(spu);

        //1.先删除子表数据
        commoditySkuMapper.deleteByMainId(spu.getId());

        commoditySkuMapper.saveBatch(skuList);
    }
    /**
     * 删除一对多--更新
     * @param id
     */
    @Override
    @Transactional
    public void delOneMain(Long id){
        commoditySkuMapper.deleteByOneMainId(id);
        commoditySpuMapper.deleteSpuById(id);
    }
    @Override
    /**
     * 批量删除一对多关系--更新
     */
    @Transactional
    public void delListBatchMain(Collection<? extends Serializable> idList){
        for (Serializable id :idList){
            commoditySkuMapper.deleteByOneMainId(Long.parseLong(id.toString()));
            commoditySpuMapper.deleteSpuById(id);
        }
    }

    /**
     * 管理端查询spu、sku信息
     * @param page
     * @param queryWrapper
     * @return
     */
    @Override
    public IPage<ProductMsg> findByPage(Page page, QueryWrapper<CommoditySpu> queryWrapper) {
       IPage<CommoditySpu> spuIPage =commoditySpuMapper.getShopPageList(page,queryWrapper);
       IPage<ProductMsg> productMsgIPage=new Page<>();
        productMsgIPage.setCurrent(spuIPage.getCurrent());
        productMsgIPage.setTotal(spuIPage.getTotal());
        productMsgIPage.setRecords(ObjectUtils.copyList(spuIPage.getRecords(),ProductMsg.class));
        return productMsgIPage;
    }

    @Override
    public boolean judgeIsVisible(String ids) {
        List<CommoditySpu> spuList = commoditySpuMapper.selectBatchIds(Arrays.stream(ids.split(",")).collect(Collectors.toList()));
       return spuList.stream().anyMatch(CommoditySpu::getVisible);
    }


    /**
     * 单个商品下架功能
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeProductSpuVisible(Long spuId , Boolean visible) {
        commoditySkuMapper.updateStatus(spuId, visible? CommonStatusEnum.ENABLE.getValue():CommonStatusEnum.DISABLE.getValue());
        return commoditySpuMapper.changeProductSpuVisible(visible,spuId);
    }
    @Override
    public boolean batchChangeProductSpuVisible(Collection<Long> spuIds, Boolean visible) {
        return commoditySpuMapper.batchChangeProductSpuVisible(visible, new ArrayList<>(spuIds));
    }
    /**
     * 单个商品审核
     * @param id 商品spuid
     * @param status 商品审核状态 通过  ？ 未通过
     */
    @Override
    public boolean toExamineGoods(Long id, Integer status) {
        return commoditySpuMapper.updateToExamine(id,status);
    }
    /**
     * 批量审核商品操作（0：待审核。审核标识2：审核不通过，1：审核通过）
     * @return
     */
    @Override
    public boolean batchToExamineGoods(Collection<Long> spuIds, String toExamine) {
        return  commoditySpuMapper.batchUpdateToExamine(new ArrayList(spuIds),toExamine);
    }

    /**
     * 管理端删除商品
     * @param paramVo
     * @return
     */
    @Override
    public Result<?> delete(ParamVo paramVo) {
        try{
            commoditySpuMapper.deleteBySpuId(Arrays.asList(paramVo.getSpuId().split(",")));
            commoditySkuMapper.deleteBySkuId(Arrays.asList(paramVo.getSpuId().split(",")));
        }catch (Exception e){
            return Result.error("删除失败，请重新选择需要删除的商品");
        }
        return Result.ok("删除成功");
    }

    /**
     * 通过spuid获取单个商品的信息，spu+ 一到多个sku
     * @param id
     * @return
     */
    @Override
    public ProductMsg getOneShopDetails(Long id) {
       CommoditySpu dto= commoditySpuMapper.getCommoditySpuDetails(id);
       ProductMsg productMsg=ObjectUtils.copyObject(dto,ProductMsg.class);
       if (dto!=null) {
           assert productMsg != null;
           productMsg.setProductSkuList(ObjectUtils.copyList(dto.getProductSkuList(), CommoditySkuDTO.class));
       }
       return  productMsg;
    }

    /**
     * 查询商铺条目下所有商品
     * @param spuIds
     * @return
     */
    @Override
    public List<ProductMsg> getGoodsList(List<Long>  spuIds) {
        return ObjectUtils.copyList(commoditySkuMapper.queryGoodsBySpuIds(spuIds),ProductMsg.class);
    }


    /**
     * 取某个店铺的所有商品
     * @param page
     * @param queryWrapper
     * @return
     */
    @Override
    public IPage<CommoditySpu> pageList(Page page, QueryWrapper<CommoditySpu> queryWrapper) {
        return commoditySpuMapper.getShopPageList(page,queryWrapper);
    }

    @Override
    public IPage<CommoditySpu> getShopPageListOfShop(Page page, String shopId,String entryId) {
        return commoditySpuMapper.getShopPageListOfShop(page,shopId,entryId);
    }

    @Override
    public IPage<CommoditySpu> getAppShopPageListOfShop(Page page, String shopId,String entryId) {
        return commoditySpuMapper.getAppShopPageListOfShop(page,shopId,entryId);
    }

    /**
     * 判断商品审核状态 true :通过 false: 未通过       0：待审核。1审核通过
     * @param spuId
     * @return
     */
    @Override
    public Boolean judgeToExamine(String spuId) {
      CommoditySpu spu=  commoditySpuMapper.judgeOneExamine(spuId);
      if("0".equals(spu.getToExamine())){
          return false;
      }else {
          return true;
      }
    }

    @Override
    public ProductMsg getOneShopDetailsBySkuId(Long id) {
        CommoditySpu commoditySpu=commoditySpuMapper.getOneShopDetailsBySkuId(id);
        ProductMsg productMsg=ObjectUtils.copyObject(commoditySpu,ProductMsg.class);
        if (commoditySpu!=null){
            productMsg.setProductSkuList(ObjectUtils.copyList(commoditySpu.getProductSkuList(),CommoditySkuDTO.class));
        }
        return productMsg;
    }
    /**
     * 通过商品id 获取对应的商户id
     * @param asList
     * @return
     */
    @Override
    public List<ProductMsg> getAllSellerId(List<String> asList) {
        return ObjectUtils.copyList(commoditySpuMapper.getAllSellerId(asList),ProductMsg.class);
    }

    @Override
    public Integer getProductCount() {
        return commoditySpuMapper.getAllProductCount();
    }

    @Override
    public String getSellerId(String shopId) {
        return commoditySpuMapper.getOneSellerId(shopId);
    }

    @Override
    public List<CommoditySpu> getSpuList(List<Long> collect) {
        if (collect==null||collect.isEmpty()){
            return Collections.emptyList();
        }
        return commoditySpuMapper.getSpuList(collect);
    }

}
